package com.cscec5b.inspection.service;

import com.cscec5b.inspection.config.JwtService;
import com.cscec5b.inspection.entity.Project;
import com.cscec5b.inspection.entity.User;
import com.cscec5b.inspection.repository.ProjectRepository;
import com.cscec5b.inspection.repository.UserRepository;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProjectService {

    private final ProjectRepository projectRepository;
    private final UserRepository userRepository;
    private final JwtService jwtService;
    private final HttpServletRequest request;

    public ProjectService(ProjectRepository projectRepository,
                          UserRepository userRepository,
                          JwtService jwtService,
                          HttpServletRequest request) {
        this.projectRepository = projectRepository;
        this.userRepository = userRepository;
        this.jwtService = jwtService;
        this.request = request;
    }

    public List<Project> listMyProjects() {  // 走token的项目列表
        // 从请求头拿 token
        String auth = request.getHeader("Authorization");
        if (auth == null || !auth.startsWith("Bearer ")) {
            throw new RuntimeException("缺少或非法的 Authorization 头");
        }
        String token = auth.substring(7);

        // 你的 JwtService 一般有 extractUsername / extractClaim 等方法
        String username = jwtService.extractUsername(token);
        if (username == null) {
            throw new RuntimeException("无法从 Token 中解析 username");
        }

        User u = userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("用户不存在: " + username));

        String userCode = u.getUserCode();   // 确保 User.userCode 是 String
        return projectRepository.findByMemberUserCode(userCode);
    }

    public List<Project> listByUserCode(String userCode) {
        return projectRepository.findByMemberUserCode(userCode);
    }

}
